import { PureComponent } from "react";
import { Button, Modal,ActivityIndicator,InputItem,Accordion,List,SearchBar,TabBar, PullToRefresh, ListView} from "antd-mobile"
import { connect } from 'dva';
import { handleImg, goToPage,isNull,handleOSS } from "../../utils/helper";
import { Row, Col } from 'antd';
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
import { Menu } from 'antd';
import {IntlProvider, addLocaleData,FormattedMessage} from 'react-intl';
import localeData from '../../../public/lang/data.json';
import MToast from '../../components/Util/MToast';
const { SubMenu } = Menu;
let pageIndex = 0;
function genData(pIndex,NUM_ROWS) {
  const dataBlob = {};
  for (let i = 0; i < NUM_ROWS; i++) {
    const ii = (pIndex * NUM_ROWS) + i;
    dataBlob[`${ii}`] = `row - ${ii}`;
    console.log(dataBlob)
  }
  return dataBlob;
}
@connect(() => {
  return ({

  })
})
export default class Category extends PureComponent{

  constructor(props){
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2 // rowHasChanged(prevRowData, nextRowData); 用其进行数据变更的比较
    })
    this.state = {
      categoryItem:[],
      categoryChild:[],
      openKeys: [],
      rootSubmenuKeys:[],
      defaultSelectedKeys:[],
      code:'',
      goodsItem:[],
      loading:true,
      loading1:true,
      isDown:false,
      selectedTab: 'blueTab',
      isButton:false,
      isOpen:false,
      dataSource,
      newsList:[],
      pages:{
        pageNum:1,
        pageSize:20
      },
      hasMore: true,
      refreshing: true,
      isLoading: true,
      IsImage:false,
      height: document.documentElement.clientHeight,
      useBodyScroll: true,
      noLogin:false,
    }
  }
  componentDidUpdate() {
    if (this.state.useBodyScroll) {
      document.body.style.overflow = 'auto';
    } else {
      document.body.style.overflow = 'hidden';
    }
  }
  componentWillMount(){
    let {dispatch,location} = this.props;
    var arr=[];
   this.categoryList(this.state.pages)
    if(localStorage[MI_APP_CODE + "phone"]==undefined){
      this.setState({
        noLogin:false
      })
    }else{
      this.setState({
        noLogin:true
      })
    }
  }
  categoryList=(pages)=>{
    let {dispatch,location} = this.props;
    dispatch({
      type: "form/query",
      payload: {
        apiInfo: {
          url: "qry/all?_c=category_list_show",
          params: [
          ],
          _c: "category_list_show"
        },
        callback: (result) => {
          let { data } = result;
          console.log(data)
          this.rData = genData(0,data.length);
          this.setState({
            categoryItem:data,
            dataSource: this.state.dataSource.cloneWithRows(this.rData),
            isLoading: false,
            loading:false,
          })



        }
      }
    });
  }
  onRefresh=()=>{
    this.setState({ refreshing: true, isLoading: true });
    // simulate initial Ajax
    setTimeout(() => {
      this.rData = genData(0,this.state.categoryItem.length);
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(this.rData),
        refreshing: false,
        isLoading: false,
      });
    }, 600);

  }
  // 滑动到底部时加载更多
  onEndReached = (event) => {//触底加载
    if (this.state.isLoading && !this.state.hasMore) {
      return;
    }
    console.log('reach end', event);
    this.setState({ isLoading: true });
    setTimeout(() => {
      this.rData = { ...this.rData, ...genData(++pageIndex) };
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(this.rData),
        isLoading: false,
      });
    }, 1000);
  }
  handleCategory=(e,i)=>{
    let {dispatch} = this.props;
    goToPage({ dispatch, config: { url: "/category_page?code="+i.parent_id+"&name="+i.name}, isReplace: false })
  }
  sidebarMenu(){
    let {categoryItem,code,defaultSelectedKeys} = this.state;
    if (!categoryItem || categoryItem.length == 0) {
      return (
        <div style={{ padding: "40px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
          {T(localeData[localStorage.locale].goodsDetailCartNoGood)}
        </div>
      )
    }
    else{
      return(
      <Row >
        {categoryItem.map((i,k)=>(
          <Col  span={6} key={i.code} onClick={(e)=>{this.handleCategory(e,i)}} style={{padding:'10px 10px 16px'}}>
            <img src={handleOSS(i.img_url)} style={{width:'73px',height:'73px'}}/>
            <p  className="ellipsis4" style={{color:'#303133',marginTop:'10px',}}>{i.name}</p>
          </Col>
        ))}

      </Row>

      )
    }
  }
  handleImageLoaded=()=>{
    let {IsImage}=this.state;
    this.setState({
      IsImage:true
    })
  }
  render(){
    let {dispatch} = this.props;
    let {cartItems,loading,modal2,currentQuantity,modal3,currentItem_id,categoryItem,categoryChildItem,
      defaultSelectedKeys,isOpen,IsImage,noLogin} = this.state;
    const messages = localeData[localStorage.locale];
    if (loading) {
      return (
        <div className="normal">
          <ActivityIndicator toast text={messages.loading} animating={true} />
        </div>
      )
    }
    const separator = (sectionID, rowID) => (
      <div
        key={`${sectionID}-${rowID}`}
        style={{
          backgroundColor: '#F5F5F9',
          height: 8,
          borderTop: '1px solid #ECECED',
          borderBottom: '1px solid #ECECED',
        }}
      />
    );
    console.log(this.state.dataSource)
    let index = categoryItem.length - 1;
    const row = (rowData, sectionID, rowID) => {
      if (index < 0) {
        index = categoryItem.length - 1;
      }
      const obj = categoryItem[index--];
      console.log(categoryItem,obj);
      if (!categoryItem || categoryItem.length == 0) {
        return (
          <div style={{ padding: "40px 0", textAlign: "center", fontSize: "20px", color: "#555" }}>
            {T(localeData[localStorage.locale].goodsDetailCartNoGood)}
          </div>
        )
      }else{
        return (

          <div style={{margin:'0 3% 6% 0%',height:'168px',float:'left',width:'30%'}}>
            <div  key={rowID} onClick={(e)=>{this.handleCategory(e,obj)}} style={{background:'#fff',border:'2px solid #F2F6FC',borderRadius:'65px',textAlign:'center'}} className="item">
              {IsImage?
                <img src={handleOSS(obj.img_url)} style={{width:'96px',borderRadius:'50%',height:'96px'}} onLoad={this.handleImageLoaded}/>
                :<img src="image/falls.png" style={{width:'96px',borderRadius:'50%',height:'96px'}}   onLoad={this.handleImageLoaded}/>}

              <p  className="ellipsis4" style={{color:'#303133',marginTop:'10px',textAlign:'center',}}>{obj.name}</p>
            </div>
          </div>

        )
      }


    };

    return(
      <IntlProvider
        locale={ localStorage.locale } messages={messages}
      >
      <div style={{height:"100%",width:'100%',padding:'10px 0',background:"#fff"}}>
        <div maxLength={8} style={{position:'fixed',top:'2%',left:'10%',width:'80%',zIndex:'100',height:'42px',border:'1px solid #ddd',borderRadius:'20px',background:"#fff",lineHeight:'42px'}} onClick={()=>{goToPage({ dispatch, config: { url: "/searchPage" }, isReplace: false })}}>
          <div style={{position:'absolute',top:'0%',left:'5%'}}>
            <img src="image/search_24px.png" style={{width:'24px',height:'24px'}}/><span style={{color:'#C9C9C9',fontSize:'13px'}}>{messages.searchPlaceholder}</span>
          </div>
        </div>
        <div style={{paddingTop:'17%'}}>
          {/*{this.sidebarMenu()}*/}
          <ListView
            ref={el => this.lv = el}
            dataSource={this.state.dataSource}
            renderRow={row}
            onEndReachedThreshold={10}
            onEndReached={this.onEndReached}
            pageSize={5}
            scrollEventThrottle={1}
            className="category"
            useBodyScroll
            renderFooter={() => (<div style={{ padding:'0px 0px 40px' , textAlign: 'center' }}>
              {this.state.isLoading ? 'Loading...' : 'Loaded'}
            </div>)}
            pullToRefresh={<PullToRefresh
              refreshing={this.state.refreshing}
              onRefresh={this.onRefresh}
            />}
          >

          </ListView>
        </div>

        <div style={{position:'fixed',bottom:'0px',left:'0px',width:'100%'}}> <TabBar
          unselectedTintColor="#949494"
          tintColor="#F09600"
          barTintColor="white"
          hidden={this.state.hidden}
        >
          <TabBar.Item
            title={messages.home}
            key="Life"
            icon={<div style={{
              width: '24px',
              height: '24px',
              background: 'url(image/home2.png) center center /  21px 21px no-repeat' }}
            />
            }
            selectedIcon={<div style={{
              width: '24px',
              height: '24px',
              background: 'url(image/home3.png) center center /  21px 21px no-repeat' }}
            />
            }
            selected={this.state.selectedTab === 'redTab'}
            onPress={() => {
              this.setState({
                selectedTab: 'redTab',
              });
              goToPage({ dispatch, config: { url: "/shop_home" }, isReplace: false })
            }}
            data-seed="logId"
          >

          </TabBar.Item>
          <TabBar.Item
            icon={
              <div style={{
                width: '24px',
                height: '24px',
                background: 'url(image/category.png) center center /  21px 21px no-repeat' }}
              />
            }
            selectedIcon={
              <div style={{
                width: '24px',
                height: '24px',
                background: 'url(image/category1.png) center center /  21px 21px no-repeat' }}
              />
            }
            title={messages.category}
            key="Koubei"

            selected={this.state.selectedTab === 'blueTab'}
            onPress={() => {
              this.setState({
                selectedTab: 'blueTab',
              });
              goToPage({ dispatch, config: { url: "/category" }, isReplace: false })
            }}
            data-seed="logId1"
          >

          </TabBar.Item>
          {noLogin?<TabBar.Item
            icon={
              <div style={{
                width: '24px',
                height: '24px',
                background: 'url(image/cart4.png) center center /  21px 21px no-repeat' }}
              />
            }
            selectedIcon={
              <div style={{
                width: '24px',
                height: '24px',
                background: 'url(image/cart5.png) center center /  21px 21px no-repeat' }}
              />
            }
            title={messages.cart}
            key="Friend"
            selected={this.state.selectedTab === 'greenTab'}
            onPress={() => {
              this.setState({
                selectedTab: 'greenTab',
              });
              goToPage({ dispatch, config: { url: "/goodcart" }, isReplace: false });
              localStorage.setItem("cart",'0')
            }}
          >
          </TabBar.Item>
            :
            <TabBar.Item
              icon={
                <div style={{
                  width: '24px',
                  height: '24px',
                  background: 'url(image/cart4.png) center center /  21px 21px no-repeat' }}
                />
              }
              selectedIcon={
                <div style={{
                  width: '24px',
                  height: '24px',
                  background: 'url(image/cart5.png) center center /  21px 21px no-repeat' }}
                />
              }
              title={messages.cart}
              key="Friend"
              selected={this.state.selectedTab === 'greenTab'}
              onPress={() => {
                this.setState({
                  selectedTab: 'greenTab',
                });
                goToPage({ dispatch, config: { url: "/ungoodcart" }, isReplace: false });
                localStorage.setItem("cart",'0')
              }}
            >
            </TabBar.Item>
          }

          <TabBar.Item
            icon={ <div style={{
              width: '24px',
              height: '24px',
              background: 'url(image/my.png) center center /  24px 24px no-repeat' }}
            />}
            selectedIcon={ <div style={{
              width: '24px',
              height: '24px',
              background: 'url(image/my1.png) center center /  24px 24px no-repeat' }}
            />}
            title={messages.my}
            key="my"
            selected={this.state.selectedTab === 'yellowTab'}
            onPress={() => {
              this.setState({
                selectedTab: 'yellowTab',
              });
              goToPage({ dispatch, config: { url: "/my" }, isReplace: false })
            }}
          >
          </TabBar.Item>
        </TabBar></div>
      </div>
      </IntlProvider>
    )
  }
}
